﻿using SuperSocket.Client.Proxy;
using System;
using System.Net;

namespace SuperSocket.Client.HttpCode;

public sealed class HttpProxyItem
{
    public HttpProxyItem()
    {
    }

    public HttpProxyItem(string ip, int port, SocketProxyType type)
        : this(ip, port, null, null, type)
    {
    }

    public HttpProxyItem(string ip, int port, string user, string pass, SocketProxyType type)
    {
        if (IPAddress.TryParse(ip, out IPAddress address))
            RemoteEndPoint = new IPEndPoint(address, port);
        else
            RemoteEndPoint = new DnsEndPoint(ip, port, System.Net.Sockets.AddressFamily.InterNetwork);

        Type = type;
        Username = user;
        Password = pass;
    }

    public HttpProxyItem(EndPoint proxy, string user, string pass, SocketProxyType type)
    {
        Type = type;
        Username = user;
        Password = pass;
        RemoteEndPoint = proxy;
    }

    public HttpProxyItem(EndPoint proxy, SocketProxyType type)
        : this(proxy, null, null, type)
    {
        Type = type;
        RemoteEndPoint = proxy;
    }

    public EndPoint RemoteEndPoint { get; set; }

    public SocketProxyType Type { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }

    internal IConnector CreataConnector(IConnector sslConnector = null)
    {
        if (RemoteEndPoint == null)
            throw new ArgumentNullException(nameof(RemoteEndPoint));

        //return new SocketConnector(sslConnector);

        if (Type == SocketProxyType.Socket5)
            return new Socks5Connector(
                proxyEndPoint: RemoteEndPoint,
                username: Username,
                password: Password,
                nextConnector: sslConnector);

        return new HttpConnector(
            proxyEndPoint: RemoteEndPoint,
            username: Username,
            password: Password,
            nextConnector: sslConnector);
    }
}